package client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.swing.JOptionPane;

import server.Commands;

public class Connector extends Thread {
	private String host;
	private int port;
	private InputStream is;
	private OutputStream os;
	private JournalViewer currentViewer;
	
	
	public Connector(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void connect() {
		SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
				.getDefault();
		try {
			SSLSocket sock = (SSLSocket) factory.createSocket(host, port);
			sock.setUseClientMode(true);
			
			sock.startHandshake();
			is = sock.getInputStream();
			os = sock.getOutputStream();
			(new Thread(this)).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void run() {
		int action = 0;
		while (true) {
			try {
				action = is.read();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (action == Commands.FILENOTFOUND) {
				JOptionPane.showMessageDialog(null, "File not found.");
			} else if (action == Commands.FILEFOUND) {
				String s = reciveData(is);
				s = (s.substring(0, (s.length() / 2) - 1)).trim();
				currentViewer = new JournalViewer(this, s.substring(s.indexOf('/') + 1, s
						.indexOf("\n")), s.substring(s.indexOf("\n") + 1, s
						.length()));
			} else if(action == Commands.SAVESUCCESFUL) {
				currentViewer.dispose();
				JOptionPane.showMessageDialog(null, "Save succesful!");
			} else if(action == Commands.SAVEUNSUCCESFUL) {
				
			} else if(action == Commands.DELETESUCCESFUL) {
				JOptionPane.showMessageDialog(null, "File deleted.");
			} else if(action == Commands.ACCESSDENIED) {
				JOptionPane.showMessageDialog(null, "Access denied!");
			}
		}
	}

	public void createNewViewer(String fileName){
		currentViewer = new JournalViewer(this, fileName, "");
	}
	
	public void setAction(int action) {
		try {
			os.write(action);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendString(String s) {
		try {
			os.write(s.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String reciveData(InputStream input) {
		byte[] byteArray = new byte[100000];
		while (true) {
			try {
				input.read(byteArray);
				return new String(byteArray);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

}
